package com.david.viewtest.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.OverScroller;

public class SmoothScrollExample extends View {

    private OverScroller mScroller;
    private int mLastX;
    private int mLastY;

    public SmoothScrollExample(Context context, AttributeSet attrs) {
        super(context, attrs);
        mScroller = new OverScroller(context);
    }

    @Override
    public void computeScroll() {
        if (mScroller.computeScrollOffset()) {
            scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
            postInvalidate();
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int x = (int) event.getX();
        int y = (int) event.getY();

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (!mScroller.isFinished()) {
                    mScroller.abortAnimation();
                }
                mLastX = x;
                mLastY = y;
                break;
            case MotionEvent.ACTION_MOVE:
                int deltaX = x - mLastX;
                int deltaY = y - mLastY;
                scrollBy(-deltaX, -deltaY);
                mLastX = x;
                mLastY = y;
                break;
            case MotionEvent.ACTION_UP:
                mScroller.fling(getScrollX(), getScrollY(), -10, -10, 0, 100, 0, 100);
                invalidate();
                break;
        }
        return true;
    }
}

